package com.gexiaobao.pigeon.app.util

import android.content.Context
import com.arthenica.mobileffmpeg.Config
import com.arthenica.mobileffmpeg.FFmpeg
import me.hgj.jetpackmvvm.util.LogUtils
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStreamWriter

/**
 * @Author      : hxw
 * @Date        : 2025/2/6 11:28
 * @Describe    :
 */
object VideoMerger {

    private const val TAG = "VideoMerger"

    fun mergeVideos(context: Context, videoPaths: ArrayList<String>, outputPath: String, callback: (String?) -> Unit) {
        // 验证文件路径是否存在
        for (path in videoPaths) {
            if (!File(path).exists()) {
                LogUtils.debugInfo(TAG, "File does not exist: $path")
                callback(null)
                return
            }
        }

        // 创建一个包含所有视频文件路径的文本文件
        val listFile = createListFile(context, videoPaths)
        if (listFile == null) {
            callback(null)
            LogUtils.debugInfo(TAG, "Failed to create list file.")
            return
        }

        // FFmpeg 命令合成视频文件
        val ffmpegCommand = "-y -f concat -safe 0 -i ${listFile.absolutePath} -c copy $outputPath"
        val rc = FFmpeg.execute(ffmpegCommand)
        if (rc == Config.RETURN_CODE_SUCCESS) {
            callback(outputPath)
            LogUtils.debugInfo(TAG, "Video merging succeeded.")
        } else {
            callback(null)
            LogUtils.debugInfo(TAG, "Video merging failed. RC: $rc")
            val output = Config.getLastCommandOutput()
            LogUtils.debugInfo(TAG, "FFmpeg output: $output")
        }
    }

    private fun createListFile(context: Context, videoPaths: ArrayList<String>): File? {
        val listFile = File(context.cacheDir, "video_list.txt")
        try {
            FileOutputStream(listFile).use { fos ->
                OutputStreamWriter(fos).use { osw ->
                    for (path in videoPaths) {
                        osw.write("file '$path'\n")
                    }
                    osw.flush()
                }
            }
        } catch (e: IOException) {
            LogUtils.debugInfo("Error writing list file", e.toString())
            return null
        }
        return listFile
    }
}